<script setup>
import { ref, onMounted } from 'vue'
import { ElCard, ElTable, ElTableColumn, ElMessage } from 'element-plus'
import { listDepartment, getDepartment, delDepartment, addDepartment, updateDepartment } from "@/api/department";

import { listAllUser } from "@/api/User";
import {Delete, Edit, Plus, Refresh, Search} from "@element-plus/icons-vue";

// 弹框状态
const formVisible = ref(false)
const title = ref('')

// 部门表单数据
const departmentForm = ref({
  name: '',
  parentId: null,
  deptCode: '',
  managerId: null
})

// 部门树形数据
const parentDepartments = ref([])
// 用户数据
const allUsers = ref([])

// 是否为编辑状态
const isEditMode = ref(false)

// 当前编辑的部门ID
const currentDepartmentId = ref(null)


// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ]
}

// // 获取部门树形结构 与 列表数据
const getDepartmentTreeData = () => {
  listDepartment({
    // name: queryForm.value.name
  }).then(res => {
    if (res.code === 200) {
      parentDepartments.value = res.data
    }
  })
}

const getAllUser = () => {
  listAllUser({
    // name: queryForm.value.name
  }).then(res => {
    if (res.code === 200) {
      allUsers.value = res.data
    }
  })
}


// 提交部门表单
const handleSubmit = () => {
    console.log(departmentForm.value,789)

    // 检查部门名称是否为空
    if (!departmentForm.value.name) {
        ElMessage.warning('请输入部门名称');
        return;
    }
    const apiMethod = isEditMode.value 
        ? updateDepartment 
        : addDepartment;

    const requestData = {
        id: currentDepartmentId.value,
        deptName: departmentForm.value.name,
        deptCode: departmentForm.value.deptCode,
        managerId: departmentForm.value.managerId,
        parentId: departmentForm.value.parentId
    };

    apiMethod(requestData).then(res => {
        if (res.code === 200) {
            ElMessage.success(`${isEditMode.value ? '更新' : '新增'}成功`);
            formVisible.value = false;
            resetForm();
            getDepartmentTreeData();
        }
    });
}

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  currentDepartmentId.value = null;
  departmentForm.value = { name: '', parentId: null, deptCode: '', managerId: null};
}

// 新增部门
const addDepartmentData = () => {
  
  isEditMode.value = false;
  resetForm();
  formVisible.value = true
  title.value = '新增部门'
}

// 获取部门树形结构

// 删除部门
const deleteDepartmentData = (row) => {
  console.log(row,"删除")
  delDepartment(row.id).then(res => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getDepartmentTreeData()
    }
  }).catch(err => {
    ElMessage.error('删除失败')
  })
}

// 编辑部门
const editDepartmentData = (row) => {
  title.value = '编辑部门'
  resetForm();
  //根据id获取部门详情
  getDepartment(row.id).then(res => {
    if (res.code === 200) {
      isEditMode.value = true;
      currentDepartmentId.value = row.id;
      departmentForm.value = {
        name: res.data.deptName,
        parentId: res.data.parentId,
        deptCode: res.data.deptCode,
        managerId:  res.data.managerId
      }
      formVisible.value = true
    }
  })
}

// 搜索框绑定的部门名称
const queryForm = ref({
    name: ''
})

// 按部门名称搜索的方法
const handleSearch = () => {
  //判断是否为空
  if(!queryForm.value.name){
    ElMessage.warning('请输入部门名称');
    return;
  }
  const params = {
    name: queryForm.value.name
  }
  getDepartmentTree(params).then(res => {
    if (res.code === 200) {
      parentDepartments.value = res.data
    }
  })
}

// 重置搜索条件
const handleReset = () => {
  queryForm.value.name = ''
  getDepartmentTreeData()
}

onMounted(() => {
  getDepartmentTreeData()
  getAllUser()
})

</script>


<template>
    <!-- 新增搜索框 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="margin-top: 10px;">
      <el-form-item>
        <el-space>
          <el-input v-model="queryForm.name" placeholder="部门名称" clearable :prefix-icon="Search">
            <template #append>
              <el-button type="primary" :icon="Search" :style="$globalAttribute.primaryButton" @click="handleSearch">
                搜索
              </el-button>
            </template>
          </el-input>
          <el-button type="primary" :icon="Refresh" plain @click="handleReset">
            重置
          </el-button>
          <el-button plain type="primary" :icon="Plus" @click="addDepartmentData">
            新增部门
          </el-button>
        </el-space>
        </el-form-item>
    </el-form>

  <el-dialog v-model="formVisible" :title="title" width="30%">
        <el-form :model="departmentForm" :rules="rules" label-width="100px">
            <el-form-item label="部门名称" prop="name">
                <el-input v-model="departmentForm.name" />
            </el-form-item>
            <el-form-item label="上级部门">
                <!-- 使用级联选择器 -->
                <el-tree-select
                    v-model="departmentForm.parentId" placeholder="请选择上级部门"
                    :data="parentDepartments"
                    node-key="id"
                    :props="{label:'deptName',children:'children'}"
                    check-strictly
                    :render-after-expand="false"
                    style="width: 100%"
                ></el-tree-select>

            </el-form-item>
<!--  -->
            <el-form-item label="部门编号" prop="deptCode">
                <el-input v-model="departmentForm.deptCode" />
            </el-form-item>
            
            <!-- <el-form-item label="部门负责人" prop="managerId">
                <el-input v-model="departmentForm.managerId" />
            </el-form-item> -->
            
            <el-form-item label="部门负责人">
              <el-select
                v-model="departmentForm.managerId"
                clearable
                placeholder="Select"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allUsers"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>

            </el-form-item>
            <div class="dialog-footer">
                <el-button @click="formVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </div>
        </el-form>
    </el-dialog>
    <!-- <el-table :data="departmentList" height="580px"> -->
      <el-table
        :data="parentDepartments"
        height="80%"
        style="width: 100%;margin-top: 10px;margin-bottom: 20px;"
        row-key="id"
        :default-expand-all="false"
       :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="deptName" label="部门名称" align="left"/>
        <el-table-column prop="deptCode" label="部门编号" align="center"/>
        <el-table-column prop="managerName" label="部门负责人" align="center"/>

        <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-space>
                <el-link type="primary" link :icon="Edit" @click="editDepartmentData(scope.row)">编辑</el-link>
                <el-link type="danger" link :icon="Delete" @click="deleteDepartmentData(scope.row)">删除</el-link>
              </el-space>
            </template>
        </el-table-column>
    </el-table>

</template>



<style scoped lang='less'>
    .mb-4 {
        margin-bottom: 1rem;
    }
    .dialog-footer {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px;
    }

    // 添加级联面板样式
    :deep(.cascader-popper) {
        .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
        color: #409EFF;
        &::after {
            content: '（可选）';
            font-size: 12px;
            color: #999;
        }
        }
    }

</style>

